package a51qindian.com.comprehensive.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.li.utils.TransformUtil;
import com.li.widget.DoubleTextView;
import com.li.widget.MultipleLayout;
import com.li.widget.TopNavigationBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import a51qindian.com.comprehensive.R;
import a51qindian.com.comprehensive.base.QDBaseActivity;
import a51qindian.com.comprehensive.model.BaseModel;
import a51qindian.com.comprehensive.model.UserDetailInfo;
import a51qindian.com.comprehensive.net.ObservableHelper;
import a51qindian.com.comprehensive.net.RetrofitCreator;
import a51qindian.com.comprehensive.net.SelectorObserver;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;


/**
 * Author: Li
 * Date: 2017/9/25 0025
 * Description: 提现界面
 */

public class GetCrashActivity extends QDBaseActivity implements View.OnClickListener {

    @BindView(R.id.top_navigation)
    TopNavigationBar mTopNavigation;
    @BindView(R.id.layout_content)
    MultipleLayout mLayoutContent;

    @BindView(R.id.txt_choose_type)
    DoubleTextView mTxtChooseType;
    @BindView(R.id.et_money)
    EditText mEtMoney;
    @BindView(R.id.et_account)
    EditText mEtAccount;
    @BindView(R.id.btn_confirm)
    Button mBtnConfirm;
    @BindView(R.id.txt_total)
    DoubleTextView mTxtTotal;
    @BindView(R.id.txt_balance)
    DoubleTextView mTxtBalance;
    @BindView(R.id.et_name)
    EditText mEtName;
    @BindView(R.id.layout_name)
    LinearLayout mLayoutName;
    @BindView(R.id.txt_money)
    TextView mTxtMoney;
    @BindView(R.id.txt_real_money)
    DoubleTextView mTxtRealMoney;


    private String mGetType;
    private RelativeLayout mLayoutZfb;
    private RelativeLayout mLayoutUnion;
    private TextView mTxtZfb;
    private TextView mTxtUnion;
    private PopupWindow mGetTypePop;
    private String mTax;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_get_crash;
    }

    @Override
    protected void initSth() {
        super.initSth();
        showBalance(mUid, "android");
        mTax = "0";
        mTopNavigation.setNavigationBarListener(this);
        mGetType = "支付宝提现";
        mTxtChooseType.setTxtRight(mGetType);
        mEtMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    mTxtRealMoney.setTxtRight("0");
                } else {
                    try {
                        if (TextUtils.isEmpty(mTax)) {
                            mTax = "0";
                        }
                        double tax = 1 - Double.parseDouble(mTax) / 100;
                        double real = Double.valueOf(s.toString());
                        String money = TransformUtil.keep2points(tax * real);
                        mTxtRealMoney.setTxtRight(money);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    @Override
    public void onFunctionTxtListener(View view) {
        startActivity(new Intent(GetCrashActivity.this, GetCrashDetailActivity.class));
    }

    @OnClick({R.id.txt_choose_type, R.id.btn_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_choose_type:
                showPop();

                break;
            case R.id.btn_confirm:

                if (checkIsEmpty(mEtMoney)||checkIsEmpty(mEtAccount)||checkIsEmpty(mEtName)) {
                    showToast("请填写全部信息");
                    return;
                }
                withdrawApply(mEtMoney.getText().toString(),
                        mTxtChooseType.getTxtRight(),
                        mEtName.getText().toString(),
                        mEtAccount.getText().toString());
                break;
        }
    }

    /**
     * 显示提现类型弹出框
     */
    private void showPop() {
        if (mGetTypePop == null) {
            @SuppressLint("InflateParams")
            View view = LayoutInflater.from(GetCrashActivity.this).inflate(R.layout.pop_layout_type, null);
            mGetTypePop = new PopupWindow(view, -1, -1);
            mLayoutZfb = view.findViewById(R.id.layout_zfb);
            mLayoutUnion = view.findViewById(R.id.layout_union);
            mTxtZfb = mLayoutZfb.findViewById(R.id.txt_zfb);
            mTxtUnion = mLayoutUnion.findViewById(R.id.txt_union);
            mLayoutZfb.setSelected(true);
            Button btnConfirm = view.findViewById(R.id.btn_confirm);
            mLayoutZfb.setOnClickListener(this);
            mLayoutUnion.setOnClickListener(this);
            btnConfirm.setOnClickListener(this);
        }
        mGetTypePop.showAtLocation(mTopNavigation, Gravity.NO_GRAVITY, 0, 0);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_zfb:
                mLayoutZfb.setSelected(true);
                mLayoutUnion.setSelected(false);
                mGetType = mTxtZfb.getText().toString();
                break;

            case R.id.layout_union:
                mLayoutZfb.setSelected(false);
                mLayoutUnion.setSelected(true);
                mGetType = mTxtUnion.getText().toString();
                break;

            case R.id.btn_confirm:
                mTxtChooseType.setTxtRight(mGetType);
                mGetTypePop.dismiss();
                break;
        }
    }

    /**
     * 提现申请
     *
     * @param money   金额
     * @param type    提现类型  支付宝、银联
     * @param name    收款人
     * @param account 收款账号  银行卡号  支付宝账号
     */
    private void withdrawApply(String money, String type, String name, String account) {
        mLayoutContent.onLoadingWithContent("加载中");
        Map<String, String> map = new HashMap<>();
        map.put("uid", mUid);
        map.put("money", money);
        map.put("bank_name", type);
        map.put("account_name", name);
        map.put("account_bank", account);
        ObservableHelper.createObservable(RetrofitCreator.createService().withdrawApply(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        mLayoutContent.onSuccess();
                        try {
                            JSONObject object = new JSONObject(s);
                            showToast(object.getString("info"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 获取余额和收益信息
     *
     * @param uid     用户编号
     * @param request 请求类型  此处为android
     */
    private void showBalance(String uid, String request) {
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("request", request);
        ObservableHelper.createObservable(RetrofitCreator.createService().userDetailInfo(map))
                .subscribe(new SelectorObserver<BaseModel<UserDetailInfo>>() {
                    @Override
                    protected void onErrorCodeInfo(int code, String info) {

                    }

                    @Override
                    protected void onSuccess(BaseModel<UserDetailInfo> userDetailInfoBaseModel) {
                        UserDetailInfo detailInfo = userDetailInfoBaseModel.getData();
                        mTxtTotal.setTxtRight(detailInfo.getTotal_money());
                        mTxtBalance.setTxtRight(detailInfo.getMoney());
                        mTax = detailInfo.getTax();
                        String tax = String.valueOf("提现金额(含税" + detailInfo.getTax() + "%" + ")：");
                        mTxtMoney.setText(tax);
                    }

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mTxtTotal.setTxtRight("获取收益失败");
                        mTxtBalance.setTxtRight("获取余额失败");
                    }
                });

    }

    @Override
    public void onBackPressed() {
        if (mGetTypePop != null && mGetTypePop.isShowing()) {
            mGetTypePop.dismiss();
            return;
        }
        super.onBackPressed();
    }


}
